package com.yfp.common.core.text;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;

/**
 * BigDecimal序列化器
 * 保留两位小数
 */
public class BigDecimalSerializer extends JsonSerializer<BigDecimal> {

    private final DecimalFormat decimalFormat = new DecimalFormat("#0.00");

    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value != null) {
            String formattedValue = decimalFormat.format(value);
            gen.writeString(formattedValue);
        } else {
            String formattedValue = decimalFormat.format(BigDecimal.ZERO);
            gen.writeString(formattedValue);
        }
    }
}